﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CRM.UTIL
{
    public class EnumBase
    {
        /// <summary>
        /// 返回指定枚举类型的列表集合用于数据绑定等
        /// </summary>
        /// <param name="t">枚举类型</param>
        /// <returns></returns>
        public static SortedList GetSortedList(Type t)
        {
            SortedList list = new SortedList();
            Array a = Enum.GetValues(t);
            for (int i = 0; i < a.Length; i++)
            {
                string enumName = a.GetValue(i).ToString();
                int enumKey = (int)System.Enum.Parse(t, enumName);
                string enumDescription = GetDescription(t, enumKey);
                list.Add(enumKey, enumDescription);
            }
            return list;
        }

        /// <summary>
        /// 返回指定枚举类型的列表集合用于数据绑定等，并加入一个未选择项
        /// </summary>
        /// <param name="t">枚举类型</param>
        /// <param name="unSelectedName">未选择项的 name</param>
        /// <param name="unSelectedValue">未选择项的 value ，默认为 -1</param>
        /// <returns></returns>
        public static SortedList GetSortedList(Type t, string unSelectedName, int unSelectedValue = -1)
        {
            var list = GetSortedList(t);
            list.Add(unSelectedValue, unSelectedName);
            return list;
        }

        public static string GetName(System.Type t, object v)
        {
            try
            {
                return Enum.GetName(t, Convert.ChangeType(v, Enum.GetUnderlyingType(t)));
            }
            catch
            {
                return "未知";
            }
        }


        /// <summary>
        /// 返回指定枚举类型的指定值的描述
        /// </summary>
        /// <param name="t">枚举类型</param>
        /// <param name="v">枚举值</param>
        /// <returns></returns>
        public static string GetDescription(System.Type t, object v)
        {
            try
            {
                FieldInfo fi = t.GetField(GetName(t, v));
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                return (attributes.Length > 0) ? attributes[0].Description : GetName(t, v);
            }
            catch
            {
                return "未知";
            }
        }
    }
}
